package com.first.nell.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.first.nell.network.NetworkException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

open class BaseViewModel : ViewModel(), BaseViewModelAction {

    private val mFirstNellLiveFirstNellDataFirstNellLoading = MutableLiveData<Boolean>()
    private val mFirstNellLiveFirstNellDataFirstNellNetFirstNellException = MutableLiveData<NetworkException>()

    open fun eventFirstNellAction(
        showLoading: Boolean = true,
        doing: suspend () -> Unit,
        error: suspend (Throwable) -> Unit,
        completed: suspend () -> Unit,
    ) {
        if (showLoading) {
            mFirstNellLiveFirstNellDataFirstNellLoading.value = true
        }
        viewModelScope.launch(Dispatchers.IO) {
            try {
                doing()
            } catch (e: Exception) {
                error(e)
            } finally {
                completed()
            }
        }
    }

    override fun showFirstNellLoading() {
        mFirstNellLiveFirstNellDataFirstNellLoading.value = true
    }

    override fun dismissFirstNellLoading() {
        mFirstNellLiveFirstNellDataFirstNellLoading.value = false
    }

    override fun handleFirstNellNetworkFirstNellException(networkException: NetworkException) {
        mFirstNellLiveFirstNellDataFirstNellNetFirstNellException.value = networkException
    }

    override fun getFirstNellLoadingFirstNellLiveFirstNellData(): MutableLiveData<Boolean> {
        return mFirstNellLiveFirstNellDataFirstNellLoading
    }

    override fun getFirstNellNetworkFirstNellExceptionFirstNellLiveFirstNellData(): MutableLiveData<NetworkException> {
        return mFirstNellLiveFirstNellDataFirstNellNetFirstNellException
    }
}